#include "strategy.h"
#include "options.h"

CLimitedCacheMemory::CLimitedCacheMemory(uint32 max_msg_size,uint32 max_block_size)
:max_msg_size_(max_msg_size),max_block_size_(max_block_size)
{
	cur_msg_size_ = cur_msg_count_ = 0;
	cur_block_size_ = cur_block_count_ = 0;
}

struct block* CLimitedCacheMemory::alloc_block()
{
	char* buf = new char[g_options.max_message_size];
	block* ret = MyNew block(buf);
	cur_block_size_ += g_options.max_message_size+sizeof(block);
	++cur_block_count_;
	return ret;
}

void CLimitedCacheMemory::free_block(struct block*& bk)
{
	if(cur_block_size_>max_block_size_)
	{
		delete[] bk->buffer;
		delete bk;
		bk = 0;
		--cur_block_count_;
		cur_block_size_ -= g_options.max_message_size+sizeof(block);
	}
}

struct msg*	 CLimitedCacheMemory::alloc_msg()
{
	msg* ret = MyNew msg();
	cur_msg_size_ += sizeof(msg);
	++cur_msg_count_;
	return ret;
}

void CLimitedCacheMemory::free_msg(struct msg*& ptr_msg)
{
	if(cur_msg_size_>max_msg_size_)
	{
		delete ptr_msg;
		ptr_msg = 0;
		--cur_msg_count_;
		cur_msg_size_ -= sizeof(msg);
	}
}

void CLimitedCacheMemory::force_free_block(struct block* ptr_block)
{
	if(ptr_block)
	{
		delete[] ptr_block->buffer;
		delete ptr_block;
	}
		
}

void CLimitedCacheMemory::force_free_msg(struct msg* ptr_msg)
{
	if(ptr_msg)
		delete ptr_msg;
}